<template>
  <div class="ckeditor_box_out">
    <iframe :src="src" ref="iframe" frameborder="0" class="ckeditor_box_iframe"></iframe>
  </div>
</template>

<script>
import {mapState} from 'vuex'

const path = require('path')

let htmlPath = ''

let remote = ''

htmlPath = `/static/ckeditor.html`

export default {
  name: 'CKEditor',
  data() {
    return {
      src: htmlPath,
      CKEDITOR: null
    }
  },
  computed: {
    ...mapState({
      caseInfo: state => state.appearCourt.caseInfo
    }),
    editor() {
      return this.CKEDITOR.instances.editor
    },
    iFrameWindow() {
      return this.CKEDITOR.iFrameWindow
    },
    editorWindow() {
      return this.editor.container.$.querySelector(`#${this.editor.id}_contents iframe`).contentWindow
    }
  },
  mounted() {
    window.addEventListener('initEditor', this.initEditor)
  },
  methods: {
    /**
     * 插入一个元素
     * @param elementName
     * @param text
     * @param styles
     * @param attributes
     * @param eventListeners
     */
    /* eslint-disable new-cap */
    insertElement(elementName = 'span', text = '', styles = {}, attributes = {}, eventListeners = {}) {
      let element = new this.CKEDITOR.dom.element(elementName)
      element.appendText(text)
      for (let eventName in eventListeners) {
        element.on(eventName, eventListeners[eventName])
      }
      // element.on('click', ev => {
      //   console.log('这是一个点击事件');
      // });
      element.setStyles(styles)
      element.setAttributes(attributes)
      this.editor.insertElement(element)
    },
    /**
     * 获取输入框的html字符串
     */
    getData() {
      return this.editor.getData()
    },
    /**
     * 设置编辑框的内容
     */
    setData(html = '') {
      this.editor.setData(html, () => {
        this.setDefaultSetting()
        this.$emit('refresh')
      })
    },
    /**
     * 光标位置插入html
     */
    insertHtml(html) {
      try {
        this.editor.insertHtml(html)
      } catch (e) {
        console.error(e)
      }
    },
    ckeditorBoxResize() {
      let toolbar = this.editor.container.$.querySelector(`#${this.editor.id}_top`)
      let contents = this.editor.container.$.querySelector(`#${this.editor.id}_contents`)
      let bottom = this.editor.container.$.querySelector(`#${this.editor.id}_bottom`)
      contents.style.height =
          this.iFrameWindow.innerHeight -
          (toolbar ? toolbar.offsetHeight : 0) -
          (bottom ? bottom.offsetHeight : 0) + 'px'

      let iframe = this.editor.container.$.querySelector(`#${this.editor.id}_contents iframe`)

      iframe.style.width = '160mm'
      iframe.style.margin = '0 auto'
      iframe.style.position = 'absolute'
      iframe.style.left = '0'
      iframe.style.right = '0'
      // iframe.style.border = '80px solid rgba(204,204,204,0.1)';
      iframe.style.borderTop = '0'
      iframe.style.borderBottom = '0'

      contents.style.textAlign = 'center'
      contents.style.background = '#e6e6e6'
      contents.style.overflowX = 'auto'
      contents.style.position = 'relative'
    },
    initEditor(e) {
      this.CKEDITOR = e.detail.CKEDITOR
      this.editor.on('instanceReady', () => {
        // let toolbar_collapser = this.editor.container.$.querySelector(`#${this.editor.id}_toolbar_collapser`)
        // toolbar_collapser && toolbar_collapser.addEventListener('click', ev => {
        //   this.ckeditorBoxResize();
        // });
        this.iFrameWindow.addEventListener('resize', ev => {
          this.$nextTick(() => {
            this.ckeditorBoxResize()
          })
        })
        this.editor.on('drop', ev => {
          console.log('drop')
          this.$emit('drop', ev)
        })
        this.editor.on('paste', ev => {
          console.log('paste')
          this.$emit('paste', ev)
        })

        this.editor.on('blur', ev => {
          console.log('blur')
          // this.editor.execCommand('mysave');
          this.$emit('save', this.editor.getData(), false)
        })

        // this.autoSave = setInterval(() => {
        //   this.editor.execCommand('mysave');
        // }, 5000);

        this.editor.addCommand('insertCatalog', {
          exec: editor => {
            this.$emit('insertCatalog')
          }
        })

        this.editor.addCommand('paste', {
          exec: editor => {
            // this.$emit('paste');
            this.editor.document.$.execCommand('paste')
          }
        })

        this.editor.addCommand('mysave', {
          editorFocus: false,
          exec: editor => {
            this.$emit('save', editor.getData(), true)
          }
        })

        this.editor.on('afterPaste', ev => {
          this.$emit('refresh')
        })

        this.$nextTick(() => {
          this.ckeditorBoxResize()
        })
        this.setDefaultSetting()
        this.$emit('loaded')
      })
      window.removeEventListener('initEditor', this.initEditor)
    },
    setDefaultSetting() {
      this.editor.document.$.body.style.fontFamily = '仿宋'
      this.editor.document.$.body.style.fontSize = '12pt'

      let flag = true

      function dragstart(ev) {
        flag = false
        // return false;
      }

      let drop = ev => {
        if (flag) {
          ev.preventDefault()
          ev.stopPropagation()
          ev.dataTransfer.dropEffect = 'copy'
        }
        if (ev.type === 'dragover') return
        if (flag) {
          let _window = window.top !== window.self ? window.top : window
          let dataTransfer = ev.dataTransfer
          let dragEvent = new DragEvent('drop', {dataTransfer})
          _window.top.dispatchEvent(dragEvent)
        } else {
          flag = true
        }
      }

      this.editor.document.$.body.ondrop = drop
      this.editor.document.$.body.ondragover = drop
      this.editor.document.$.body.ondragstart = dragstart
    }
  },
  props: {},
  beforeDestroy() {
    window.removeEventListener('resize', this.ckeditorBoxResize)
    // this.editor.destroy();
    // this.autoSave && clearInterval(this.autoSave);
    console.log('编辑器销毁')
  }
}
</script>

<style scoped>
.ckeditor_box_out {
  width: 100%;
  height: 100%;
  font-size: 14px;
  position: relative !important;
}

.ckeditor_box_iframe {
  width: 100%;
  height: 100%;
  /*width: 146.6mm;*/
  border: none;
  position: absolute;
  top: 0;
}

</style>
